<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'  // 添加这行引入
import { userPasswordUpdate } from '@/api/user'
import router from '@/router/index.js';
import { useTokenStore } from '@/stores/token'
import useUserInfoStore from '@/stores/userInfo'
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()
const passwordDate = ref({
    oldPwd: '',
    newPwd: '',
    rePwd: ''
})
// 校验密码的函数
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'));
    } else if (value !== passwordDate.value.newPwd) {
        callback(new Error('两次输入密码不一致!'));
    } else {
        callback();
    }
}
const rules = {
    oldPwd: [
        { required: true, message: '请输入原始密码', trigger: 'blur' },
        {
            pattern: /^\S{5,16}$/,
            message: '原始密码必须是5-16位非空字符串',
            trigger: 'blur'
        }
    ],
    newPwd: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度在 5 ~ 16 位非空字符串', trigger: 'blur' }
    ]
    ,
    rePwd: [
        { validator: checkRePassword, trigger: 'blur' }
    ]
}


const updatePWD = async () => {
    let res = await userPasswordUpdate(passwordDate.value)
    ElMessage.success(res.message ? res.message : "修改成功，请重新登录")
    userInfoStore.removeInfo()
    tokenStore.removeToken()
    router.push('/login')
}
</script>
<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>重置密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form :model="passwordDate" :rules="rules" label-width="100px" size="large">
                    <el-form-item label="原始密码" prop="oldPwd">
                        <el-input type="password" placeholder="请输入原始密码" v-model="passwordDate.oldPwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="newPwd">
                        <el-input type="password" placeholder="请输入新密码" v-model="passwordDate.newPwd"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="rePwd">
                        <el-input type="password" placeholder="请再次输入密码" v-model="passwordDate.rePwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="updatePWD">提交修改</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>